//
//  PxReaderView.h
//  Express
//
//  Created by 泰然财富 on 15/7/28.
//  Copyright (c) 2015年 泰然财富. All rights reserved.
//

#import "PxEditableTableViewCell.h"
#import "LLSmallUtil.h"
#import "UIView+Sizes.h"
#import "PxFormValidate.h"

@implementation PxEditableTableViewCell {

}

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.textLabel.hidden = YES;
    }
    return self;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    self.textField = [[PxTextField alloc] initWithFrame:self.textLabel.frame];
    self.textField.backgroundColor = [UIColor whiteColor];
    self.textField.width = self.detailTextLabel.left - self.textLabel.left;
    self.textField.text = self.textLabel.text;
    self.textField.font = self.textLabel.font;
    self.textField.textColor = self.textLabel.textColor;
    self.textField.delegate = self;
    self.textField.keyboardType = UIKeyboardTypePhonePad;
    self.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.contentView addSubview:_textField];
}

-(void)changPhone:(NSString *)phone
{
    self.textLabel.text = phone;
    self.textLabel.hidden = YES;
    if (_delegate)
        [_delegate dataChanged:self.indexPath andValue:phone];
}

-(BOOL)checkPhone:(NSString *)phone
{
    BOOL isOk = [[PxFormValidate sharedInstance] checkPhone:phone];
    if (!isOk) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"手机号不符合现有规则，是否继续"] preferredStyle: UIAlertControllerStyleAlert];
        UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action){
            [self changPhone:phone];
        }];
        UIAlertAction *CancelAction = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action){
            [self.textField setText:self.textLabel.text];
        }];
        [alertController addAction:OKAction];
        [alertController addAction:CancelAction];
        
        [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
        return NO;
    }
    
    return YES;
}

#pragma mark textField delegate

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSString *value = textField.text;
    BOOL isOk = [self checkPhone:textField.text];
    if (isOk)
        [self changPhone:value];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.text.length >= 10 && string.length > 0) {
        if (textField.text.length == 10)
            [textField setText:[NSString stringWithFormat:@"%@%@", textField.text, string]];
        [textField resignFirstResponder];
        return NO;
    }
    
    return YES;
}

@end